/*
 * @Author: silence
 * @Date: 2022-11-18 17:02:40
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-11-27 18:06:45
 * @Description: 
 */

import 'package:bot_toast/bot_toast.dart';
import 'package:demo_trtc_live/config.dart';
import 'package:demo_trtc_live/pages/ShowVideoPage.dart';
import 'package:demo_trtc_live/utils/GenerateTestUserSig.dart';
import 'package:demo_trtc_live/utils/TrtcUtils.dart';
import 'package:flutter/material.dart';
import 'package:tencent_trtc_cloud/trtc_cloud_def.dart';
import 'package:tencent_trtc_cloud/trtc_cloud_listener.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<String> _list = ['进入房间', '退出房间', '开始视频会议'];

  @override
  void initState() {
    super.initState();

    /// 初始化trtc
    TrtcUtils.init();
    TrtcUtils.onRtcListener = (type, param) {
      if (type == TRTCCloudListener.onError) {
        BotToast.showText(text: '进入房间失败');
      }

      if (type == TRTCCloudListener.onEnterRoom) {
        if (param > 0) {
          BotToast.showText(text: '进入房间成功');
        }
      }

      if (type == TRTCCloudListener.onExitRoom) {
        BotToast.showText(text: '退出房间成功');
      }

      if (type == TRTCCloudListener.onUserVideoAvailable) {
        BotToast.showText(text: '可以开始视频会议了');
      }
    };
  }

  @override
  Widget build(BuildContext context) {
    return mainWidget();
  }

  mainWidget() {
    return ListView.separated(
        itemBuilder: (context, index) {
          return listItem(index);
        },
        separatorBuilder: (context, index) {
          return Container(
              height: 0.5, color: Color.fromRGBO(135, 135, 135, 1));
        },
        itemCount: _list.length);
  }

  listItem(index) {
    return Container(
      child: TextButton(
          onPressed: () {
            switch (index) {
              case 0:
                enterRoom();
                break;
              case 1:
                exitRoom();
                break;
              case 2:
                // 开始视频会议
                Navigator.push(context,
                    MaterialPageRoute(builder: (context) => ShowVideoPage()));
                break;
              default:
            }
          },
          child: Text(_list[index])),
    );
  }

  /// 进入房间
  enterRoom() {
    TrtcUtils.entryRoom(
        sdkAppId: Config.sdkAppId,
        userId: Config.userId,
        userSig: GenerateTestUserSig.genTestSig(Config.userId),
        roomId: Config.roomId,
        role: TRTCCloudDef.TRTCRoleAudience);

    TrtcUtils.registerListenerHanlder();
  }

  /// 退出房间
  exitRoom() {
    TrtcUtils.exitRoom();
    TrtcUtils.removeRegisterListener();
  }
}
